package maa.action.admin.mentor;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.*;
import maa.dao.h2.MentorDAOimpl;
import maa.dao.h2.UserDAOimpl;
import maa.dao.DAOCommand;
import maa.database.ConnectionPool;
import maa.entity.Mentor;
import maa.action.ActionException;
import maa.dao.DAOException;
import maa.util.FieldValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class AddMentor implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws ActionException {
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        final UUID uuid = (UUID) session.getAttribute("id");
        final Mentor mentor = new Mentor(uuid);
        String rang = req.getParameter("rang");
        String info = req.getParameter("info");
        String experience = req.getParameter("experience");
        if (!FieldValidator.isValidRang(rang)) {
            req.setAttribute("incorrect_rang", "Invalid rang");
            actionResult.setResult("mentor-creation");
            return actionResult;
        }
        if (!FieldValidator.isValidInfo(info)) {
            req.setAttribute("incorrect_info", "Invalid information");
            actionResult.setResult("mentor-creation");
            return actionResult;
        }
        if (!FieldValidator.isValidWorkExperience(experience)) {
            req.setAttribute("incorrect_experience", "Invalid work experience");
            actionResult.setResult("mentor-creation");
            return actionResult;
        }
        mentor.setRang(rang);
        mentor.setInfo(info);
        mentor.setWorkExperience(Double.parseDouble(experience));
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                MentorDAOimpl mentorDAO = daoManager.getMentorDAO();
                UserDAOimpl userDAO = daoManager.getUserDAO();
                try {
                    if (userDAO.switchRoleToMentor(uuid) && mentorDAO.create(mentor))
                        return true;
                } catch (DAOException e) {
                    throw new ActionException("Exception in userDAO.switchRoleToMentor(uuid) and mentorDAO.create(mentor)");
                }
                return false;
            }
        };
        daoManager.transactionAndClose(command);
        actionResult.setResult("success");
        actionResult.setRedirected(true);
        return actionResult;
    }
}
